<template>
	<view class="edit-container">
		<view class="header">
			<text class="title">编辑菜品</text>
			<button class="back-btn" @click="handleBack">返回</button>
		</view>

		<view class="content">
			<view class="form-card">
				<view class="form-header">
					<text class="form-title">菜品信息</text>
				</view>

				<view class="form-body">
					<view class="form-item">
						<text class="label required">菜品名称</text>
						<input 
							v-model="formData.name" 
							class="input" 
							placeholder="请输入菜品名称"
							maxlength="50"
						/>
						<text class="error" v-if="errors.name">{{ errors.name }}</text>
					</view>

					<view class="form-item">
						<text class="label required">菜品分类</text>
						<picker 
							mode="selector" 
							:range="categoryOptions" 
							range-key="name"
							@change="handleCategoryChange"
							:value="categoryIndex"
						>
							<view class="picker">
								{{ categoryIndex >= 0 ? categoryOptions[categoryIndex].name : '请选择分类' }}
							</view>
						</picker>
						<text class="error" v-if="errors.category_id">{{ errors.category_id }}</text>
					</view>



					<view class="form-item">
						<text class="label">菜品描述</text>
						<textarea 
							v-model="formData.description" 
							class="textarea" 
							placeholder="请输入菜品描述"
							maxlength="200"
						/>
						<text class="char-count">{{ formData.description?.length || 0 }}/200</text>
					</view>

					<view class="form-item">
						<text class="label">菜品图片</text>
						<view class="image-upload">
							<input 
								v-model="formData.image" 
								class="input" 
								placeholder="请输入图片URL（可选）"
							/>
							<button class="preview-btn" @click="previewImage" v-if="formData.image">预览</button>
						</view>
						<view class="image-preview" v-if="formData.image">
							<image :src="formData.image" mode="aspectFit" class="preview-image"></image>
						</view>
					</view>

					<view class="form-item">
						<text class="label">主材</text>
						<textarea 
							v-model="formData.ingredients.main_ingredients" 
							class="textarea" 
							placeholder="请输入主材（可选）"
							maxlength="500"
						/>
					</view>

					<view class="form-item">
						<text class="label">辅材</text>
						<textarea 
							v-model="formData.ingredients.auxiliary_ingredients" 
							class="textarea" 
							placeholder="请输入辅材（可选）"
							maxlength="500"
						/>
					</view>

					<view class="form-item">
						<text class="label required">辣度</text>
						<view class="radio-group">
							<label class="radio-label">
								<radio :checked="formData.spiciness === 0" @click="formData.spiciness = 0" />
								<text>不辣</text>
							</label>
							<label class="radio-label">
								<radio :checked="formData.spiciness === 1" @click="formData.spiciness = 1" />
								<text>微辣</text>
							</label>
							<label class="radio-label">
								<radio :checked="formData.spiciness === 2" @click="formData.spiciness = 2" />
								<text>中辣</text>
							</label>
							<label class="radio-label">
								<radio :checked="formData.spiciness === 3" @click="formData.spiciness = 3" />
								<text>重辣</text>
							</label>
						</view>
						<text class="error" v-if="errors.spiciness">{{ errors.spiciness }}</text>
					</view>

					<view class="form-item">
						<text class="label">是否推荐</text>
						<switch :checked="formData.is_recommended" @change="onRecommendChange" />
					</view>
				</view>

				<view class="form-actions">
					<button class="btn btn-cancel" @click="handleBack">取消</button>
					<button class="btn btn-submit" @click="handleSubmit">保存</button>
				</view>
			</view>
		</view>

		<!-- 图片预览弹窗 -->
		<uni-popup ref="imagePopup" type="center">
			<view class="image-modal">
				<image :src="formData.image" mode="aspectFit" class="modal-image"></image>
				<button class="close-btn" @click="closeImagePreview">关闭</button>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const dishId = ref('')

const formData = reactive({
	name: '',
	category_id: '',
	description: '',
	image: '',
	ingredients: {
		main_ingredients: '',
		auxiliary_ingredients: '',
		seasonings: ''
	},
	spiciness: 0,
	is_recommended: false
})

const errors = reactive({})
const categoryOptions = ref([])
const categoryIndex = ref(-1)
const imagePopup = ref(null)

onLoad(async (options) => {
	if (options.id) {
		dishId.value = options.id
	}
	// 先加载分类，再加载详情，避免分类未加载时无法匹配索引
	await loadCategories()
	if (options.id) {
		await loadDishDetail()
	}
})

async function loadDishDetail() {
	uni.showLoading({ title: '加载中...' })
	try {
		const result = await uniCloud.callFunction({
			name: 'food-dishes',
			data: { action: 'get-dish-detail', data: { dishId: dishId.value } }
		})
		if (result.result.code === 200) {
			const dishData = result.result.data
			formData.name = dishData.name || ''
			formData.category_id = dishData.category_id || ''
			formData.description = dishData.description || ''
			formData.image = dishData.image || ''
			formData.ingredients.main_ingredients = (dishData.ingredients && dishData.ingredients.main_ingredients) || ''
			formData.ingredients.auxiliary_ingredients = (dishData.ingredients && dishData.ingredients.auxiliary_ingredients) || ''
			formData.ingredients.seasonings = (dishData.ingredients && dishData.ingredients.seasonings) || ''
			formData.spiciness = parseInt(dishData.spiciness) || 0
			formData.is_recommended = !!dishData.is_recommended

			if (formData.category_id) {
				const index = categoryOptions.value.findIndex(cat => cat._id === formData.category_id)
				if (index >= 0) categoryIndex.value = index
			}
		} else {
			uni.showToast({ title: result.result.message || '获取菜品详情失败', icon: 'none' })
		}
	} catch (error) {
		console.error('获取菜品详情失败:', error)
		uni.showToast({ title: '获取详情失败', icon: 'none' })
	} finally {
		uni.hideLoading()
	}
}

async function loadCategories() {
	try {
		const result = await uniCloud.callFunction({
			name: 'food-categories',
			data: { action: 'get-categories', data: { pageSize: 100 } }
		})
		if (result.result.code === 200) {
			categoryOptions.value = result.result.data.list || []
			// 如果详情已加载且已有分类ID，尝试匹配并设置分类索引
			if (formData.category_id) {
				const index = categoryOptions.value.findIndex(cat => cat._id === formData.category_id)
				if (index >= 0) categoryIndex.value = index
			}
		}
	} catch (error) {
		console.error('加载分类失败:', error)
	}
}

function handleCategoryChange(e) {
	categoryIndex.value = e.detail.value
	if (categoryIndex.value >= 0) {
		formData.category_id = categoryOptions.value[categoryIndex.value]._id
	} else {
		formData.category_id = ''
	}
}

function validateForm() {
	// 重置错误
	errors.name = ''
	errors.category_id = ''
	errors.spiciness = ''
	let isValid = true

	if (!formData.name.trim()) {
		errors.name = '菜品名称不能为空'
		isValid = false
	} else if (formData.name.trim().length > 50) {
		errors.name = '菜品名称不能超过50个字符'
		isValid = false
	}

	if (!formData.category_id) {
		errors.category_id = '请选择菜品分类'
		isValid = false
	}

	const s = parseInt(formData.spiciness)
	if (isNaN(s) || s < 0 || s > 3) {
		errors.spiciness = '辣度必须是0-3之间的整数'
		isValid = false
	}

	return isValid
}

async function handleSubmit() {
	if (!validateForm()) return
	uni.showLoading({ title: '保存中...' })
	try {
		const submitData = {
			name: formData.name.trim(),
			category_id: formData.category_id,
			description: formData.description?.trim() || '',
			image: formData.image || '',
			ingredients: {
				main_ingredients: formData.ingredients.main_ingredients?.trim() || '',
				auxiliary_ingredients: formData.ingredients.auxiliary_ingredients?.trim() || '',
				seasonings: formData.ingredients.seasonings?.trim() || ''
			},
			spiciness: parseInt(formData.spiciness),
			is_recommended: !!formData.is_recommended
		}

		const result = await uniCloud.callFunction({
			name: 'food-dishes',
			data: { action: 'update-dish', data: { dishId: dishId.value, updateData: submitData } }
		})

		if (result.result.code === 200) {
			uni.showToast({ title: '保存成功', icon: 'success' })
			setTimeout(() => { uni.redirectTo({ url: '/pages/dishes/list' }) }, 1200)
		} else {
			uni.showToast({ title: result.result.message || '保存失败', icon: 'none' })
		}
	} catch (error) {
		console.error('保存菜品失败:', error)
		uni.showToast({ title: '保存失败', icon: 'none' })
	} finally {
		uni.hideLoading()
	}
}

function handleBack() { uni.redirectTo({ url: '/pages/dishes/list' }) }

function previewImage() {
	if (formData.image) imagePopup.value?.open()
}

function onRecommendChange(e) {
  formData.is_recommended = !!(e && e.detail && e.detail.value)
}

function closeImagePreview() { imagePopup.value?.close() }
</script>

<style lang="scss" scoped>
	.edit-container {
		min-height: 100vh;
		background-color: #f5f5f5;

		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			background: white;
			border-bottom: 1rpx solid #eee;

			.title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}

			.back-btn {
				padding: 16rpx 32rpx;
				background: #f0f0f0;
				border: none;
				border-radius: 8rpx;
				font-size: 28rpx;
				color: #666;
				cursor: pointer;
			}
		}

		.content {
			padding: 20rpx;

			.form-card {
				background: white;
				border-radius: 12rpx;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

				.form-header {
					padding: 30rpx;
					border-bottom: 1rpx solid #eee;

					.form-title {
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
					}
				}

				.form-body {
					padding: 30rpx;

					.form-item {
						margin-bottom: 40rpx;

						&:last-child {
							margin-bottom: 0;
						}

						.label {
							display: block;
							font-size: 28rpx;
							color: #333;
							margin-bottom: 15rpx;

							&.required::after {
								content: '*';
								color: #ff4d4f;
								margin-left: 5rpx;
							}
						}

						.input {
							width: 100%;
							padding: 20rpx;
							border: 1rpx solid #d9d9d9;
							border-radius: 8rpx;
							font-size: 28rpx;
							color: #333;

							&:focus {
								border-color: #007aff;
							}
						}

						.textarea {
							width: 100%;
							padding: 20rpx;
							border: 1rpx solid #d9d9d9;
							border-radius: 8rpx;
							font-size: 28rpx;
							color: #333;
							min-height: 120rpx;
							resize: vertical;

							&:focus {
								border-color: #007aff;
							}
						}

						.char-count {
							display: block;
							text-align: right;
							font-size: 24rpx;
							color: #999;
							margin-top: 10rpx;
						}

						.picker {
							padding: 20rpx;
							border: 1rpx solid #d9d9d9;
							border-radius: 8rpx;
							font-size: 28rpx;
							color: #333;
							background: white;
						}

						.image-upload {
							display: flex;
							gap: 15rpx;

							.preview-btn {
								padding: 16rpx 24rpx;
								background: #007aff;
								color: white;
								border: none;
								border-radius: 6rpx;
								font-size: 26rpx;
								cursor: pointer;
							}
						}

						.image-preview {
							margin-top: 15rpx;

							.preview-image {
								width: 200rpx;
								height: 150rpx;
								border-radius: 8rpx;
								border: 1rpx solid #eee;
							}
						}

						.radio-group {
							display: flex;
							gap: 30rpx;

							.radio-label {
								display: flex;
								align-items: center;
								gap: 10rpx;
								font-size: 28rpx;
								color: #333;
								cursor: pointer;
							}
						}

						.error {
							display: block;
							font-size: 24rpx;
							color: #ff4d4f;
							margin-top: 10rpx;
						}
					}
				}

				.form-actions {
					display: flex;
					gap: 20rpx;
					padding: 30rpx;
					border-top: 1rpx solid #eee;

					.btn {
						flex: 1;
						padding: 24rpx;
						border: none;
						border-radius: 8rpx;
						font-size: 28rpx;
						cursor: pointer;

						&.btn-cancel {
							background: #f0f0f0;
							color: #666;
						}

						&.btn-submit {
							background: #007aff;
							color: white;
						}
					}
				}
			}
		}

		.image-modal {
			background: white;
			border-radius: 12rpx;
			padding: 30rpx;
			text-align: center;

			.modal-image {
				width: 400rpx;
				height: 300rpx;
				border-radius: 8rpx;
				margin-bottom: 20rpx;
			}

			.close-btn {
				padding: 16rpx 32rpx;
				background: #007aff;
				color: white;
				border: none;
				border-radius: 8rpx;
				font-size: 28rpx;
				cursor: pointer;
			}
		}

		@media (max-width: 750rpx) {
			.edit-container {
				padding: 15rpx;

				.header {
					padding: 15rpx;

					.title {
						font-size: 32rpx;
					}

					.back-btn {
						padding: 12rpx 24rpx;
						font-size: 26rpx;
					}
				}

				.content {
					padding: 15rpx;

					.form-card {
						.form-header {
							padding: 20rpx;

							.form-title {
								font-size: 30rpx;
							}
						}

						.form-body {
							padding: 20rpx;

							.form-item {
								margin-bottom: 30rpx;

								.image-upload {
									flex-direction: column;
									gap: 10rpx;

									.preview-btn {
										width: 100%;
									}
								}
							}
						}

						.form-actions {
							padding: 20rpx;
							flex-direction: column;
							gap: 15rpx;
						}
					}
				}

				.image-modal {
					padding: 20rpx;

					.modal-image {
						width: 300rpx;
						height: 200rpx;
					}
				}
			}
		}
	}
</style>